<template>
  <div class="sql-editor-wrapper">
    <div class="editor-toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button size="small" @click="formatSQL">
            <el-icon><MagicStick /></el-icon>
            格式化
          </el-button>
          <el-button size="small" @click="clearSQL">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
          <el-button size="small" @click="showAIDialog = true">
            <el-icon><ChatDotRound /></el-icon>
            AI生成
          </el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-button size="small" type="primary" @click="handleExecute" :loading="executing">
          <el-icon><CaretRight /></el-icon>
          执行 (Ctrl+Enter)
        </el-button>
      </div>
    </div>

    <div class="editor-container">
      <div class="line-numbers">
        <div v-for="n in lineCount" :key="n" class="line-number">{{ n }}</div>
      </div>
      <textarea
        ref="editorRef"
        v-model="localValue"
        class="sql-editor"
        :placeholder="placeholder"
        @input="handleInput"
        @keydown="handleKeyDown"
        @scroll="handleScroll"
        spellcheck="false"
      ></textarea>
      
      <!-- 智能提示下拉框 -->
      <div 
        v-if="showSuggestions" 
        class="suggestions-popup"
        :style="suggestionsStyle"
      >
        <div 
          v-for="(suggestion, index) in filteredSuggestions"
          :key="index"
          class="suggestion-item"
          :class="{ active: index === selectedSuggestionIndex }"
          @click="selectSuggestion(suggestion)"
        >
          <el-icon class="suggestion-icon">
            <component :is="getSuggestionIcon(suggestion.type)" />
          </el-icon>
          <div class="suggestion-content">
            <span class="suggestion-name">{{ suggestion.name }}</span>
            <span class="suggestion-type">{{ suggestion.type }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="editor-status">
      <span>行: {{ currentLine }}, 列: {{ currentColumn }}</span>
      <span>字符数: {{ localValue.length }}</span>
      <span class="status-indicator" :class="{ valid: isValidSQL }">
        {{ isValidSQL ? '✓ SQL有效' : '⚠ 检查SQL' }}
      </span>
    </div>

    <!-- AI生成对话框 -->
    <el-dialog v-model="showAIDialog" title="AI生成SQL" width="600px">
      <el-alert
        title="描述你想要的SQL查询，AI会自动生成"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-input
        v-model="aiPrompt"
        type="textarea"
        :rows="4"
        placeholder="例如：查询最近30天的订单统计，按天分组"
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          生成SQL
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  MagicStick, Delete, ChatDotRound, CaretRight, 
  Coin, Grid, Document
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '输入SQL语句...\n支持智能提示和语法高亮'
  },
  tables: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'execute'])

// 状态
const editorRef = ref(null)
const localValue = ref(props.modelValue)
const showSuggestions = ref(false)
const selectedSuggestionIndex = ref(0)
const currentLine = ref(1)
const currentColumn = ref(1)
const executing = ref(false)
const showAIDialog = ref(false)
const aiPrompt = ref('')
const aiGenerating = ref(false)

// 建议提示位置
const suggestionsStyle = ref({
  top: '0px',
  left: '0px'
})

// 行数计算
const lineCount = computed(() => {
  return localValue.value.split('\n').length
})

// SQL关键字
const sqlKeywords = [
  'SELECT', 'FROM', 'WHERE', 'INSERT', 'UPDATE', 'DELETE', 'JOIN',
  'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'ORDER BY', 'GROUP BY',
  'HAVING', 'LIMIT', 'OFFSET', 'AS', 'AND', 'OR', 'NOT', 'IN',
  'LIKE', 'BETWEEN', 'IS NULL', 'IS NOT NULL', 'COUNT', 'SUM',
  'AVG', 'MAX', 'MIN', 'DISTINCT', 'CREATE', 'ALTER', 'DROP',
  'TABLE', 'INDEX', 'VIEW', 'SET', 'VALUES', 'INTO'
]

// SQL函数
const sqlFunctions = [
  'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'NOW', 'CURDATE', 'CURTIME',
  'DATE_FORMAT', 'CONCAT', 'SUBSTRING', 'LENGTH', 'UPPER', 'LOWER',
  'TRIM', 'ROUND', 'FLOOR', 'CEIL', 'ABS', 'RAND'
]

// 所有建议项
const allSuggestions = computed(() => {
  const suggestions = []
  
  // 添加关键字
  sqlKeywords.forEach(keyword => {
    suggestions.push({
      name: keyword,
      type: 'keyword',
      description: 'SQL关键字'
    })
  })
  
  // 添加函数
  sqlFunctions.forEach(func => {
    suggestions.push({
      name: func,
      type: 'function',
      description: 'SQL函数'
    })
  })
  
  // 添加表名
  props.tables.forEach(table => {
    suggestions.push({
      name: table.name,
      type: 'table',
      description: table.comment || '数据表'
    })
    
    // 添加字段
    if (table.fields) {
      table.fields.forEach(field => {
        suggestions.push({
          name: `${table.name}.${field.name}`,
          type: 'column',
          description: field.comment || '字段'
        })
      })
    }
  })
  
  return suggestions
})

// 过滤后的建议
const filteredSuggestions = computed(() => {
  if (!showSuggestions.value) return []
  
  const cursorPos = editorRef.value?.selectionStart || 0
  const textBeforeCursor = localValue.value.substring(0, cursorPos)
  const words = textBeforeCursor.split(/\s+/)
  const currentWord = words[words.length - 1]
  
  if (!currentWord) return []
  
  return allSuggestions.value.filter(s => 
    s.name.toLowerCase().startsWith(currentWord.toLowerCase())
  ).slice(0, 10)
})

// 简单的SQL验证
const isValidSQL = computed(() => {
  if (!localValue.value.trim()) return true
  
  const sql = localValue.value.toUpperCase()
  return sql.includes('SELECT') || sql.includes('INSERT') || 
         sql.includes('UPDATE') || sql.includes('DELETE') ||
         sql.includes('CREATE') || sql.includes('ALTER')
})

// 监听值变化
watch(() => props.modelValue, (newVal) => {
  if (newVal !== localValue.value) {
    localValue.value = newVal
  }
})

watch(localValue, (newVal) => {
  emit('update:modelValue', newVal)
  updateCursorPosition()
})

// 处理输入
const handleInput = (e) => {
  const value = e.target.value
  localValue.value = value
  
  // 触发智能提示
  checkSuggestions()
}

// 处理按键
const handleKeyDown = (e) => {
  // Ctrl+Enter 执行
  if (e.ctrlKey && e.key === 'Enter') {
    e.preventDefault()
    handleExecute()
    return
  }
  
  // 智能提示导航
  if (showSuggestions.value) {
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      selectedSuggestionIndex.value = Math.min(
        selectedSuggestionIndex.value + 1,
        filteredSuggestions.value.length - 1
      )
    } else if (e.key === 'ArrowUp') {
      e.preventDefault()
      selectedSuggestionIndex.value = Math.max(
        selectedSuggestionIndex.value - 1,
        0
      )
    } else if (e.key === 'Enter' || e.key === 'Tab') {
      e.preventDefault()
      if (filteredSuggestions.value[selectedSuggestionIndex.value]) {
        selectSuggestion(filteredSuggestions.value[selectedSuggestionIndex.value])
      }
    } else if (e.key === 'Escape') {
      showSuggestions.value = false
    }
  }
}

// 检查是否显示建议
const checkSuggestions = () => {
  const cursorPos = editorRef.value?.selectionStart || 0
  const textBeforeCursor = localValue.value.substring(0, cursorPos)
  const words = textBeforeCursor.split(/\s+/)
  const currentWord = words[words.length - 1]
  
  if (currentWord && currentWord.length >= 1) {
    showSuggestions.value = true
    selectedSuggestionIndex.value = 0
    updateSuggestionsPosition()
  } else {
    showSuggestions.value = false
  }
}

// 更新建议位置
const updateSuggestionsPosition = () => {
  if (!editorRef.value) return
  
  const textarea = editorRef.value
  const cursorPos = textarea.selectionStart
  
  // 简单计算位置（实际应该更精确）
  const lines = localValue.value.substring(0, cursorPos).split('\n')
  const lineNumber = lines.length
  const columnNumber = lines[lines.length - 1].length
  
  suggestionsStyle.value = {
    top: `${lineNumber * 20 + 40}px`,
    left: `${columnNumber * 8 + 50}px`
  }
}

// 选择建议
const selectSuggestion = (suggestion) => {
  const cursorPos = editorRef.value?.selectionStart || 0
  const textBeforeCursor = localValue.value.substring(0, cursorPos)
  const textAfterCursor = localValue.value.substring(cursorPos)
  
  // 找到当前单词的开始位置
  const words = textBeforeCursor.split(/\s+/)
  const currentWord = words[words.length - 1]
  const wordStart = textBeforeCursor.lastIndexOf(currentWord)
  
  // 替换当前单词
  localValue.value = 
    localValue.value.substring(0, wordStart) + 
    suggestion.name + 
    textAfterCursor
  
  showSuggestions.value = false
  
  // 设置光标位置
  nextTick(() => {
    const newPos = wordStart + suggestion.name.length
    editorRef.value.setSelectionRange(newPos, newPos)
    editorRef.value.focus()
  })
}

// 获取建议图标
const getSuggestionIcon = (type) => {
  const iconMap = {
    keyword: 'Document',
    function: 'MagicStick',
    table: 'Grid',
    column: 'Coin'
  }
  return iconMap[type] || 'Document'
}

// 更新光标位置
const updateCursorPosition = () => {
  if (!editorRef.value) return
  
  const cursorPos = editorRef.value.selectionStart
  const textBeforeCursor = localValue.value.substring(0, cursorPos)
  const lines = textBeforeCursor.split('\n')
  
  currentLine.value = lines.length
  currentColumn.value = lines[lines.length - 1].length + 1
}

// 处理滚动
const handleScroll = (e) => {
  const lineNumbers = e.target.parentElement.querySelector('.line-numbers')
  if (lineNumbers) {
    lineNumbers.scrollTop = e.target.scrollTop
  }
}

// 格式化SQL
const formatSQL = () => {
  let sql = localValue.value.trim()
  
  // 简单的SQL格式化
  sql = sql.replace(/\s+/g, ' ')
  sql = sql.replace(/,/g, ',\n  ')
  sql = sql.replace(/\bFROM\b/gi, '\nFROM')
  sql = sql.replace(/\bWHERE\b/gi, '\nWHERE')
  sql = sql.replace(/\bAND\b/gi, '\n  AND')
  sql = sql.replace(/\bOR\b/gi, '\n  OR')
  sql = sql.replace(/\bORDER BY\b/gi, '\nORDER BY')
  sql = sql.replace(/\bGROUP BY\b/gi, '\nGROUP BY')
  sql = sql.replace(/\bLIMIT\b/gi, '\nLIMIT')
  
  localValue.value = sql
  ElMessage.success('SQL已格式化')
}

// 清空SQL
const clearSQL = () => {
  localValue.value = ''
}

// 执行SQL
const handleExecute = () => {
  if (!localValue.value.trim()) {
    ElMessage.warning('请输入SQL语句')
    return
  }
  
  emit('execute', localValue.value)
}

// AI生成SQL
const handleAIGenerate = () => {
  if (!aiPrompt.value.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }
  
  aiGenerating.value = true
  
  // 模拟AI生成
  setTimeout(() => {
    const generatedSQL = generateSQLByAI(aiPrompt.value)
    localValue.value = generatedSQL
    
    ElMessage.success('SQL已生成')
    aiGenerating.value = false
    showAIDialog.value = false
    aiPrompt.value = ''
  }, 1500)
}

// 模拟AI生成SQL
const generateSQLByAI = (prompt) => {
  const lowerPrompt = prompt.toLowerCase()
  
  if (lowerPrompt.includes('查询') || lowerPrompt.includes('统计')) {
    return `SELECT 
  id,
  name,
  create_time,
  COUNT(*) as total
FROM 
  your_table
WHERE 
  create_time >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY 
  DATE(create_time)
ORDER BY 
  create_time DESC
LIMIT 100;`
  } else if (lowerPrompt.includes('插入') || lowerPrompt.includes('新增')) {
    return `INSERT INTO your_table (
  name,
  status,
  create_time
) VALUES (
  'value',
  1,
  NOW()
);`
  } else if (lowerPrompt.includes('更新') || lowerPrompt.includes('修改')) {
    return `UPDATE your_table 
SET 
  name = 'new_value',
  update_time = NOW()
WHERE 
  id = 1;`
  } else {
    return `SELECT * FROM your_table WHERE id = 1;`
  }
}

onMounted(() => {
  if (editorRef.value) {
    editorRef.value.addEventListener('click', updateCursorPosition)
  }
})
</script>

<style scoped>
.sql-editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
  background: #f5f7fa;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.editor-container {
  position: relative;
  display: flex;
  height: 300px;
  overflow: hidden;
}

.line-numbers {
  width: 40px;
  background: #f5f7fa;
  border-right: 1px solid #dcdfe6;
  overflow: hidden;
  user-select: none;
  text-align: right;
  padding: 10px 5px;
}

.line-number {
  height: 20px;
  line-height: 20px;
  color: #909399;
  font-size: 12px;
  font-family: 'Courier New', monospace;
}

.sql-editor {
  flex: 1;
  padding: 10px;
  border: none;
  outline: none;
  resize: none;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 20px;
  background: #fff;
  color: #303133;
}

.sql-editor::placeholder {
  color: #c0c4cc;
}

.suggestions-popup {
  position: absolute;
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.suggestion-item:hover,
.suggestion-item.active {
  background: #f5f7fa;
}

.suggestion-icon {
  color: #409eff;
}

.suggestion-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.suggestion-name {
  font-family: 'Courier New', monospace;
  color: #303133;
}

.suggestion-type {
  font-size: 12px;
  color: #909399;
}

.editor-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  border-top: 1px solid #dcdfe6;
  background: #f5f7fa;
  font-size: 12px;
  color: #909399;
}

.status-indicator {
  color: #f56c6c;
}

.status-indicator.valid {
  color: #67c23a;
}
</style>

